<?php

/*
 * This file is part of the HWIOAuthBundle package.
 *
 * (c) Hardware.Info <opensource@hardware.info>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace IMT\SynchBundle\OAuth\ResourceOwner;

use IMT\UserBundle\Entity\Contact;

use HWI\Bundle\OAuthBundle\OAuth\ResourceOwner\GenericOAuth2ResourceOwner;
use HWI\Bundle\OAuthBundle\Security\Core\Authentication\Token\OAuthToken;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Security\Core\Exception\AuthenticationException;

/**
 * GenericOAuth2ResourceOwner
 *
 * @author Geoffrey Bachelet <geoffrey.bachelet@gmail.com>
 * @author Alexander <iam.asm89@gmail.com>
 */
class GoogleContactResourceOwner extends GenericOAuth2ResourceOwner
{
    /**
     * @var array
     */
    protected $defaultOptions = array(
        'authorization_url'       => 'https://accounts.google.com/o/oauth2/auth',
        'access_token_url'        => 'https://accounts.google.com/o/oauth2/token',
        'revoke_token_url'        => 'https://accounts.google.com/o/oauth2/revoke',
        'infos_url'           => null,

        'user_response_class' => 'HWI\Bundle\OAuthBundle\OAuth\Response\PathUserResponse',

        'scope'               => null,
    		
    		
    	// @link https://developers.google.com/accounts/docs/OAuth2WebServer#offline
    	'access_type'             => 'offline',
    	'request_visible_actions' => null,
    	// sometimes we need to force for approval prompt (e.g. when we lost refresh token)
    	'approval_prompt'         => null,
    );
    
    public function getRedirect(){
    	return 'account_home';
    } 
    
    /**
     * {@inheritDoc}
     */
    public function getAuthorizationUrl($redirectUri, array $extraParameters = array())
    {
    	return parent::getAuthorizationUrl($redirectUri, array_merge(array(
    			'access_type'             => 'offline',
    			'approval_prompt'         => $this->getOption('approval_prompt'),
    			'request_visible_actions' => $this->getOption('request_visible_actions')
    	), $extraParameters));
    }

    /**
     * {@inheritDoc}
     */
    public function getAccountInformation($accessToken, $account, $em)
    {
        $url = $this->normalizeUrl('https://www.google.com/m8/feeds/contacts/default/full?alt=json', array(
            'access_token' => is_array($accessToken) ? $accessToken['access_token'] : $accessToken
        ));

        $content = $this->doGetContactInformationRequest($url)->getContent();
        
        $arrayContact = json_decode($content, true);
                
        $profils = $account->getUser()->getProfils();
        foreach($profils as $profil){
        	foreach($profil->getAccounts() as $accountProfil){
        		if($accountProfil->getId() == $account->getId()){
        			$profil->setEmail($arrayContact['feed']['id']['$t']);
        			
        			$em->persist($profil);
        			$em->flush();
        		}        			
        	}
        }        
        
        if(isset($arrayContact['feed']['entry'])){
	        foreach($arrayContact['feed']['entry'] as $contactNode){
	        	$email = (isset($contactNode['gd$email'][0]['address'])) ? $contactNode['gd$email'][0]['address'] : null;
	        	$name = (isset($contactNode['title']['$t'])) ? $contactNode['title']['$t'] : null;
	        	$tel = (isset($contactNode['gd$phoneNumber'][0]['$t'])) ? $contactNode['gd$phoneNumber'][0]['$t'] : null;
		        	
	        	if($email && $name){
		        	$contact = $em->getRepository('IMTUserBundle:Contact')->findBy(array(
		        		'idGoogle' => $contactNode['id']['$t'],
		        	));
		        	
		        	if(!$contact){
		        		$contact = new Contact();
		        		$contact->setIdGoogle($contactNode['id']['$t']);
		        	} else if(is_array($contact) && isset($contact[0])){
		        		$contact = $contact[0];
		        	}
		        	
		        	$contact->setName($name);
		        	$contact->setEmail($email);
		        	
		        	$account->addContact($contact);
	        	}
	        }
        }
        
        $em->persist($account);
        $em->flush();
    }
    
    public function getEventInformation($accessToken, $account, $em, $container)
    {
    	$url = $this->normalizeUrl('https://www.googleapis.com/calendar/v3/calendars/primary/events', array(
            'access_token' => is_array($accessToken) ? $accessToken['access_token'] : $accessToken
        ));

        $content = $this->httpRequest($url)->getContent();
        
        $arrayEvent = json_decode($content, true);
        
        $emEvent = $container->get('imt_event.event_manager');
        $validator = $container->get('validator');
        
        if(isset($arrayEvent['items'])){
	        foreach($arrayEvent['items'] as $eventGoogle){
	        	$event = $emEvent->findEventBy(array('idGoogle' => $eventGoogle['id']));
	        	if(!$event){
	        		$event = $emEvent->createEvent();
	        	}
	        	
	        	$event->setIdGoogle($eventGoogle['id']);
	        	$event->setImportance(0);
	        	$event->setTitle($eventGoogle['summary']);
	        	$event->setContent((isset($eventGoogle['description'])) ? $eventGoogle['description'] : '');
	        	        	
	        	if(isset($eventGoogle['start']['date'])){
		        	$date = new \DateTime($eventGoogle['start']['date']);
		        	$dateFin = new \DateTime($eventGoogle['end']['date']);
	        	} else if(isset($eventGoogle['start']['dateTime'])){
		        	$date = new \DateTime($eventGoogle['start']['dateTime']);
		        	$dateFin = new \DateTime($eventGoogle['end']['dateTime']);
	        	} 
	        	
	//         	if($request->request->get('imt_event_form_general_allDay')){
	//         		$date = new \DateTime($date->format('Y-m-d').' 00:00:00');
	//         		$dateFin = new \DateTime($dateFin->format('Y-m-d').' 23:59:59');
	//         	}
	        	$event->setDate($date);
	        	$event->setDateFin($dateFin);
	        	
	        	$event->setAllDay(0);
	        	$event->setAccounts(array($account));
	        		
	        	$errors = $validator->validate($event);
	        	 
	        	if(count($errors) == 0){
	        		try {
	        			$emEvent->updateEvent($event);
	        		} catch(\Exception $e){}
	        	}
	        }
    	}
    }
    
    /**
     * {@inheritDoc}
     */
    protected function doGetContactInformationRequest($url, array $parameters = array())
    {
    	return $this->httpRequest($url);
    }
}
